package com.wing.cabinet.controller.websocket.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wing.cabinet.controller.websocket.CabinetOpenServer;
import com.wing.cabinet.controller.websocket.service.BaseConnectService;
import com.wing.common.utils.HttpHelper;
import com.wing.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 接收柜子领新结果返馈
 *  {"client":"applets","phone":"18942503919"，"cabCode":"SKU-ZG01-20221017-1","createTime":"2024-01-23 11:32:50.341","enterpriseCode":"Z0005","type":"inventoryOutResult","byPassword":true,"detailList":[{"cabCode":"SD-20231225-01","packId":10,"packName":"一盒一支","quantity":1,"quantityPackUnit":1,"skuCode":"A0016","spaceCode":"16","unitName":""}],"deviceCode":"YK-A105","processId":14,"workOrderId":12}
 */
@Service
@Slf4j
public class InventoryOutResultServiceImpl implements BaseConnectService {

    @Override
    public void logicMessage(String message) throws IOException {
        log.debug("收到消息:"+message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        String type = jsonObject.getString("type"); //消息类型 codeSend
        String enterpriseCode = jsonObject.getString("enterpriseCode");  // 企业编号
        String cabCode = jsonObject.getString("cabCode"); //柜子编号
        String client = jsonObject.getString("client"); //客户端
        String phone = jsonObject.getString("phone"); //手机号
        String uuid = jsonObject.getString("uuid"); //手机号
        String resCode = jsonObject.getString("code"); //错误码

        JSONObject cabJsonObjet = jsonObject;
        //全部出货成功
        //进行领新逻辑
        try {
            //柜子忙: 柜子正在出货中，这笔请求不处理
            if("400".equals(resCode)){
                //jsonObject.put("successList", null);
                //jsonObject.put("failList", null);
                jsonObject.put("code", resCode);
                jsonObject.put("msg", "柜子忙: 柜子正在出货中，这笔请求不处理");
                jsonObject.put("client", "applets");
                CabinetOpenServer.sendAppletMessage(enterpriseCode, cabCode, phone, jsonObject.toJSONString());
                return;
            }
            ////((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().setHeader(SecurityConstants.JWT_PAYLOAD_KEY);
            //CellInventoryInoutDetailService cellInventoryInoutDetailService = (CellInventoryInoutDetailService) ApplicationContextUtil.getBean("cellInventoryInoutDetailServiceImpl");
            //CellInventoryInoutForm cellInventoryInoutForm = jsonObject.toJavaObject(CellInventoryInoutForm.class);
            //cellInventoryInoutForm.getDetailList().get(0).setWorkOrderId(cellInventoryInoutForm.getWorkOrderId());
            //cellInventoryInoutForm.getDetailList().get(0).setProcessId(cellInventoryInoutForm.getProcessId());
            //cellInventoryInoutDetailService.inventoryOut(cellInventoryInoutForm.getSuccessList(), cellInventoryInoutForm.getDeviceCode(), CellInventoryInout.BusinessType.cellCabOut, UseInventoryInout.BusinessType.cellCabOut, cellInventoryInoutForm.getByPassword(), cellInventoryInoutForm.getStoresRequisitionId(),uuid);
            //CabinetOpenServer.sendMessage(enterpriseCode, cabCode,message);

            Map<String,String> heards = new HashMap<>();
            heards.put("Authorization", jsonObject.getString("Authorization"));
            cabJsonObjet.put("type",null);
            //JSONObject subJSONObject = jsonObject.getJSONArray("successList");
            JSONArray subJSONArray = jsonObject.getJSONArray("successList");
            if(null != subJSONArray && subJSONArray.size() > 0){
                cabJsonObjet.put("detailList", subJSONArray);
                //ws://10.3.11.41:9306/websocket/cabOpen
                String url = jsonObject.getString("url");
                //String[] urlArray = url.split("\\/");
                //String[] ips = urlArray[2].split(":");
                String params = JSONObject.toJSONString(cabJsonObjet, SerializerFeature.DisableCircularReferenceDetect);
                log.info("长连接柜子领货请求: param:{}", params);
                String res = HttpHelper.httpPost(url+ "/enterprisecab/cabinet/app/cellInventoryInoutDetail/inventoryOut", params, heards);
                log.info("长连接柜子领货响应: res:{}", res);
                if(null == res){
                    jsonObject.put("successList", null);
                    jsonObject.put("failList", jsonObject.getString("detailList"));
                    jsonObject.put("code", Result.Code.EXCEPTION.getCode());
                    jsonObject.put("msg", Result.Code.EXCEPTION.getDesc());
                    jsonObject.put("client", "applets");
                    CabinetOpenServer.sendAppletMessage(enterpriseCode, cabCode, phone, jsonObject.toJSONString());

                    //给面板回一条反馈失败的消息
                    cabJsonObjet.put("type","inventoryOutResult");
                    cabJsonObjet.put("client","cab");
                    cabJsonObjet.put("response","反馈受理失败");
                    cabJsonObjet.put("code",500);
                    CabinetOpenServer.sendMessage(enterpriseCode, cabCode, cabJsonObjet.toJSONString());
                    return;
                }
                JSONObject inventoryResult = JSON.parseObject(res);
                String code = inventoryResult.getString("code");
                String msg = inventoryResult.getString("msg");
                if("200".equals(code)){
                    jsonObject.put("client", "applets");
                    jsonObject.put("detailList", null);
                    CabinetOpenServer.sendAppletMessage(enterpriseCode, cabCode, phone, jsonObject.toJSONString());

                    //给面板回一条反馈成功的消息
                    cabJsonObjet.put("type","inventoryOutResult");
                    cabJsonObjet.put("client","cab");
                    cabJsonObjet.put("response","反馈受理成功");
                    cabJsonObjet.put("code",200);
                    CabinetOpenServer.sendMessage(enterpriseCode, cabCode, cabJsonObjet.toJSONString());
                    return;
                }

                jsonObject.put("successList", null);
                jsonObject.put("failList", jsonObject.getString("detailList"));
                jsonObject.put("code", code);
                jsonObject.put("msg", msg);
                jsonObject.put("client", "applets");
                CabinetOpenServer.sendAppletMessage(enterpriseCode, cabCode, phone, jsonObject.toJSONString());

                //给面板回一条反馈失败的消息
                cabJsonObjet.put("type","inventoryOutResult");
                cabJsonObjet.put("client","cab");
                cabJsonObjet.put("response",msg);
                cabJsonObjet.put("code",code);
                CabinetOpenServer.sendMessage(enterpriseCode, cabCode, cabJsonObjet.toJSONString());
                return;
            }

            jsonObject.put("client", "applets");
            CabinetOpenServer.sendAppletMessage(enterpriseCode, cabCode, phone, jsonObject.toJSONString());

            //给面板回一条反馈失败的消息
            cabJsonObjet.put("type","inventoryOutResult");
            cabJsonObjet.put("client","cab");
            CabinetOpenServer.sendMessage(enterpriseCode, cabCode, cabJsonObjet.toJSONString());
            return;

        }catch (Exception e){
            log.error("cell inventory out fail",e);
            cabJsonObjet.put("type","inventoryOutResult");
            cabJsonObjet.put("client","cab");
            cabJsonObjet.put("response","反馈受理失败");
            cabJsonObjet.put("code",500);
            CabinetOpenServer.sendMessage(enterpriseCode, cabCode, cabJsonObjet.toJSONString());
        }

    }


}
